// TCPServer.cpp
#include "TCPServer.hpp"

// 构造函数
TCPServer::TCPServer(unsigned short port)
    : m_port(port), m_serverSocket(INVALID_SOCKET), m_isRunning(false) {}

// 析构函数
TCPServer::~TCPServer()
{
    stop();
}

// 启动服务器
bool TCPServer::start()
{
    // 检查是否已经启动
    if (m_isRunning)
        return false;

    // 初始化 WinSock
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        std::cerr << "WSAStartup failed." << std::endl;
        return false;
    }

    // 创建并绑定套接字
    m_serverSocket = createAndBindSocket(m_port);
    if (m_serverSocket == INVALID_SOCKET)
    {
        WSACleanup();
        return false;
    }

    // 启动服务器
    m_isRunning = true;
    m_listenThread = std::thread(&TCPServer::listenForClients, this);
    m_listenThread.detach();
    return true;
}

// 停止服务器
void TCPServer::stop()
{
    m_isRunning = false;
    if (m_listenThread.joinable())
    {
        m_listenThread.join(); // 等待监听线程结束
    }

    if (m_serverSocket != INVALID_SOCKET)
    {
        // 关闭套接字
        closesocket(m_serverSocket);
        m_serverSocket = INVALID_SOCKET;
    }

    // 关闭所有客户端套接字
    for (SOCKET sock : m_clientSockets)
    {
        if (sock != INVALID_SOCKET)
        {
            closesocket(sock);
        }
    }
    m_clientSockets.clear();

    WSACleanup(); // 释放资源
}

// 创建并绑定套接字
SOCKET TCPServer::createAndBindSocket(unsigned short port)
{
    // 创建套接字
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (serverSocket == INVALID_SOCKET)
    {
        return INVALID_SOCKET;
    }

    // 设置服务器地址
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(port);

    // 绑定套接字
    if (bind(serverSocket, (sockaddr *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
    {
        closesocket(serverSocket);
        return INVALID_SOCKET;
    }

    // 监听连接
    if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        closesocket(serverSocket);
        return INVALID_SOCKET;
    }

    return serverSocket;
}

// 监听客户端连接
void TCPServer::listenForClients()
{
    while (m_isRunning)
    {
        SOCKET clientSocket = accept(m_serverSocket, nullptr, nullptr);
        // 检查是否成功接收客户端连接
        if (clientSocket != INVALID_SOCKET)
        {
            std::cout << "Client connected." << std::endl;
            std::lock_guard<std::mutex> lock(m_clientMutex);
            m_clientSockets.push_back(clientSocket);
            // 为每个客户端创建一个新线程
            std::thread(&TCPServer::handleClient, this, clientSocket).detach();
        }
    }
}

// 接收客户端数据处理
void TCPServer::handleClient(SOCKET clientSocket)
{
    char buffer[1024] = {0};
    int bytesReceived = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
    if (bytesReceived > 0) // 接收到有效数据
    {
        buffer[bytesReceived] = '\0';
        std::cout << "Received: " << buffer << std::endl;
        std::string response = "Echo: " + std::string(buffer);
        send(clientSocket, response.c_str(), response.length(), 0);
    }
    closesocket(clientSocket); // 关闭客户端套接字
}

// 广播消息
void TCPServer::broadcastMessage(const std::string &message, SOCKET excludeSocket)
{
    std::cout << "Broadcasting message: " << message << std::endl;
    std::lock_guard<std::mutex> lock(m_clientMutex);
    // 遍历所有客户端套接字
    for (SOCKET sock : m_clientSockets)
    {
        if (sock != excludeSocket && sock != INVALID_SOCKET)
        {
            // 发送消息
            int result = send(sock, message.c_str(), message.length(), 0);
            if (result == SOCKET_ERROR)
                std::cerr << "Error sending message to client." << std::endl;
        }
    }
}